#include "Socket.hpp"
#include "Inetaddr.hpp"
#include <memory>
#include <functional>
#include <pthread.h>
using io_service_t = std::function<void*(void*)>;
class TcpServer
{
    private:
        TcpServer(int port,io_service_t service) :
        _localaddr(InetAddr("0",port)),
        _service(service),
        _listensock(std::make_unique<socket_ns::TcpSocket>())
        {
            _listensock->BuildListenSocket(_localaddr);
        }
    public:
        static TcpServer* getInstance(int port , io_service_t service = nullptr)
        {
            static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
            //获取单例对象
            if(svr == nullptr)
            {
                pthread_mutex_lock(&mutex);
                if(svr == nullptr)
                {
                    if(service != nullptr) 
                        svr = new TcpServer(port,service);
                    else 
                        ELOG("unlegal operator get instance , reason:service = nullptr");
                }
                pthread_mutex_unlock(&mutex);
            }
            return svr;
        }
        void Request()
        {
            int* sock = new int(_listensock->Sockfd());
            _service(sock);
        }
        int Sockfd(){return _listensock->Sockfd();}
        ~TcpServer(){
            _listensock->Close();
        }
        socket_ns::socket_ptr Accept(InetAddr* addr)
        {
            socket_ns::socket_ptr sock = _listensock->Accepter(addr);
            return sock;
        }
    private:
        std::unique_ptr<socket_ns::Base_Socket> _listensock;
        InetAddr _localaddr;
        io_service_t _service;
        static TcpServer* svr; //单例模式
};
TcpServer* TcpServer::svr = nullptr;